//
//  HeadScrollView.m
//  chanyouji
//
//  Created by xiacheng on 16/8/17.
//  Copyright © 2016年 chanyouji. All rights reserved.
//

#import "HeadScrollView.h"
#import "Common.h"
#import "HeaderModel.h"
#import "UIImageView+WebCache.h"
@interface HeadScrollView()<UIScrollViewDelegate>
{
    NSInteger count;
    UIPageControl *page;
}
@end
@implementation HeadScrollView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        CGRect frame = CGRectMake(0, 0,kScreenWidth,headAdvantiseHeight);
        self.frame = frame;
        //隐藏水平滑动条
        self.showsHorizontalScrollIndicator = NO;
        self.delegate = self;
        self.pagingEnabled = YES;
#warning 没有runloop也能运行。。。？？
        [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
    }
    return self;
}
//获得数据时更新
- (void)setHeadModel:(HeaderModel *)headModel {
    _headModel = headModel;
    count = self.headModel.headURLArr.count;
    self.contentSize = CGSizeMake(kScreenWidth*count,headAdvantiseHeight);
    for (NSInteger i = 0; i<count; i++) {
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(i*kScreenWidth, 0, kScreenWidth, headAdvantiseHeight)];
        NSString *imgURL = self.headModel.headURLArr[i];
        
        [self addSubview:imgView];
        [imgView sd_setImageWithURL:[NSURL URLWithString:imgURL]];
        [self creatPageController];
    }
}
// 创建pagecontrol
- (void)creatPageController {
    page = [[UIPageControl alloc]initWithFrame:CGRectMake(kScreenWidth/2-50, headAdvantiseHeight-20, 100, 20)];
    page.numberOfPages = count;
    page.pageIndicatorTintColor = [UIColor grayColor];
    page.currentPageIndicatorTintColor = [UIColor whiteColor];
    [[UIApplication sharedApplication].keyWindow addSubview:page];
    page.alpha = 0.7;
    //添加点击方法
    [page addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];
}
#pragma mark -----scrollviewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //更新UIPageControl的当前页
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.frame;
    [page setCurrentPage:offset.x / bounds.size.width];
}
#pragma mark -----page click  方法
//这个方法是智障啊，那么小怎么点，还不如滑
- (void)pageTurn:(UIPageControl *)pages {
    //令UIScrollView做出相应的滑动显示
    CGSize viewSize = self.frame.size;
    CGRect rect = CGRectMake(pages.currentPage * viewSize.width, 0, viewSize.width, viewSize.height);
    [self scrollRectToVisible:rect animated:YES];
}
- (void)timeAction:(NSTimer *)time {
    static NSInteger index = 0;
    if (index > 3) {
        index = 0;
    }
    page.currentPage = index;
    CGPoint point = CGPointMake(index*kScreenWidth, 0);
    self.contentOffset = point;
    index++;
}

@end
